import type { RouteRecordRaw, RouteComponent, Router, RouterHistory } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { name } from '../../package.json';

const pagePath: Record<string, RouteRecordRaw> = import.meta.glob('@/views/**/page.ts', {
  import: 'default',
  eager: true,
});

const modules = import.meta.glob('@/views/**/*View.vue');
const modulesMap = Object.fromEntries(
  Object.entries(modules).map(e => {
    const path = e[0];
    const tempPath = path.split('/');
    tempPath.pop();
    return [tempPath.join('/'), e[1]];
  })
);

const rootRoute = new Set<string>();
const routeMap = Object.fromEntries(
  Object.entries(pagePath).map(([path, config]) => {
    const _tempPath = path.replace('/page.ts', '');
    path = path.replace('src/views/', '').replace('/page.ts', '') || '/';
    const nameArray = path.split('/').filter(Boolean);
    const name = nameArray.join('-');
    const component = modulesMap[_tempPath];
    if (nameArray.length === 1) {
      rootRoute.add(path + '/');
    }
    // const children=
    return [
      path + '/',
      <RouteRecordRaw>{
        ...config,
        path,
        name,
        component,
      },
    ];
  })
);
const routeKey = Object.keys(routeMap);
const staticRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: {
      name: 'Demo-Table',
    },
    meta: {
      hidden: true,
    },
  },
];
export const routes: RouteRecordRaw[] = staticRoutes.concat(
  Array.from(rootRoute).map(urlPath => {
    function getChildren(path: string): RouteRecordRaw[] {
      const children: RouteRecordRaw[] = [];
      routeKey
        .filter(e => e.startsWith(path) && e.replace(path, '').split('/').length === 2)
        .forEach(e => {
          routeMap[e].children = getChildren(e);
          children.push(routeMap[e]);
        });
      return children;
    }
    const ret = routeMap[urlPath];
    ret.children = getChildren(urlPath);

    return ret;
  })
);

console.log(routes)
let router: Router = createRouter({
  history: createWebHistory(`/${name}`),
  routes,
});
let routerHistory: RouterHistory | null = createWebHistory(`/${name}`);
router.beforeEach(async (to, from) => {
  return true;
});
export default router;

export function destoryHistory() {
  routerHistory?.destroy();
  routerHistory = null;
  router = null;
}
